<template>
    <div class="audio-table-nav">
        <n-input style="width: 280px;margin-right: 10px;" v-model:value="audioSearchValue" @keydown.enter="seatchAudio" placeholder="请输入搜索关键字（歌名、歌手、作词）" />
        <n-button style="margin-right: 10px;" type="primary" @click="seatchAudio">搜索</n-button>
        <n-button style="margin-right: 10px;" type="warning" @click="showAudioLog">日志</n-button>
        <n-button v-if="userInfo.roles == 'root'" type="error" @click="delteAudio">删除</n-button>
    </div>

    <n-data-table remote bordered :single-line="false" ref="audioTable" :row-key="audioRowKey" :columns="audioColumns" :data="audioData" :loading="audioLoading" :pagination="audioPagination" @update:page="handleAudioPageChange"
        @update:checked-row-keys="handleCheck" />

    <!-- 操作音频源 -->
    <n-modal v-model:show="showReplaceAudioSrcModal" preset="dialog">
        <template #header>
            <div>切换音频源</div>
        </template>
        <div>内容</div>
        <template #action>
            <div>操作</div>
        </template>
    </n-modal>

    <!-- 操作音频封面 -->
    <n-modal v-model:show="showReplaceAudioCoverModal" preset="dialog">
        <template #header>
            <div>切换音频封面</div>
        </template>
        <div>内容</div>
        <template #action>
            <div>操作</div>
        </template>
    </n-modal>

    <!-- 操作音频歌词 -->
    <n-modal v-model:show="showReplaceLyricModal" preset="dialog">
        <template #header>
            <div>切换音频歌词</div>
        </template>
        <div>内容</div>
        <template #action>
            <div>操作</div>
        </template>
    </n-modal>

    <!-- 操作音频mv -->
    <n-modal v-model:show="showReplaceAudioMvModal" preset="dialog">
        <template #header>
            <div>切换音频MV</div>
        </template>
        <div>内容</div>
        <template #action>
            <div>操作</div>
        </template>
    </n-modal>

    <!-- 展示日志 -->
    <n-modal v-model:show="showAudioLogModal" preset="dialog">
        <template #header>
            <div>更改音频的日志</div>
        </template>
        <div>内容</div>
        <template #action>
            <div>操作</div>
        </template>
    </n-modal>
</template>
    
<script setup lang='ts'>

import { DataTableColumns, NInput, NButton, NSwitch, NSelect, DataTableRowKey, useMessage } from 'naive-ui';
import { ref, reactive, onMounted, defineComponent, nextTick, h, Component, onBeforeMount } from 'vue'
import { getAllAudio, searchAudio, updateAudioInfo, deleteAudio } from '../../../ajax'
import { useSystemConfigStore, userInfoStore } from '../../../store';
import dayjs from 'dayjs'
import { useRouter } from 'vue-router';

onBeforeMount(() => {
    if (userInfo.roles == 'user') {
        useSystemConfig.changeSetPage('systemConfig')
        router.replace({ name: 'systemConfig' })
        message.warning('没有权限用户禁止使用此功能，已跳转至系统配置')
    }
})

onMounted(async () => {
    // 获取音频列表数据
    await updateAudioData()
})


const userInfo = userInfoStore()
const useSystemConfig = useSystemConfigStore()
const router = useRouter()
const message = useMessage()


// 音乐表的数据类型
type AudioRowData = {
    _id: string,
    joinDate: number,
    audioName: string,
    singer: string,
    write: string,
    audioSrc: string,
    audioCover: string,
    lyric: string,
    audioMv: string,
    audioVersion: string,
    available: boolean,
    languagesTag: Array<string>
    styleTag: Array<string>
    sceneTag: Array<string>
    feelingTag: Array<string>
    themeTag: Array<string>
    operator: Array<string>
}
type Select = {
    label: string,
    value: string,
    disable?: boolean
}


// tag的语种枚举
const selectLanguagesOptions: Select[] = [
    {
        label: '华语',
        value: '华语'
    },
    {
        label: '欧美',
        value: '欧美'
    },
    {
        label: '日语',
        value: '日语'
    },
    {
        label: '韩语',
        value: '韩语'
    },
    {
        label: '粤语',
        value: '粤语'
    }
]
// tag的风格枚举
const selectStyleOptions: Select[] = [
    {
        label: '流行',
        value: '流行'
    },
    {
        label: '摇滚',
        value: '摇滚'
    },
    {
        label: '民谣',
        value: '民谣'
    },
    {
        label: '电子',
        value: '电子'
    },
    {
        label: '舞曲',
        value: '舞曲'
    },
    {
        label: '说唱',
        value: '说唱'
    },
    {
        label: '轻音乐',
        value: '轻音乐'
    },
    {
        label: '爵士',
        value: '爵士'
    },
    {
        label: '乡村',
        value: '乡村'
    },
    {
        label: 'R&B/Soul',
        value: 'R&B/Soul'
    },
    {
        label: '古典',
        value: '古典'
    },
    {
        label: '民族',
        value: '民族'
    },
    {
        label: '英伦',
        value: '英伦'
    },
    {
        label: '金属',
        value: '金属'
    },
    {
        label: '朋克',
        value: '朋克'
    },
    {
        label: '蓝调',
        value: '蓝调'
    },
    {
        label: '雷鬼',
        value: '雷鬼'
    },
    {
        label: '世界音乐',
        value: '世界音乐'
    },
    {
        label: '拉丁',
        value: '拉丁'
    },
    {
        label: 'New Age',
        value: 'New Age'
    },
    {
        label: '古风',
        value: '古风'
    },
    {
        label: '后摇',
        value: '后摇'
    },
    {
        label: 'Bossa Nova',
        value: 'Bossa Nova'
    },
]
// tag的场景枚举
const selectSceneOptions: Select[] = [
    {
        label: '清晨',
        value: '清晨'
    },
    {
        label: '夜晚',
        value: '夜晚'
    },
    {
        label: '学习',
        value: '学习'
    },
    {
        label: '工作',
        value: '工作'
    },
    {
        label: '午休',
        value: '午休'
    },
    {
        label: '下午茶',
        value: '下午茶'
    },
    {
        label: '地铁',
        value: '地铁'
    },
    {
        label: '驾车',
        value: '驾车'
    },
    {
        label: '运动',
        value: '运动'
    },
    {
        label: '旅行',
        value: '旅行'
    },
    {
        label: '散步',
        value: '散步'
    },
    {
        label: '酒吧',
        value: '酒吧'
    },
]
// tag的情感枚举
const selectFeelingOptions: Select[] = [
    {
        label: '怀旧',
        value: '怀旧'
    },
    {
        label: '清新',
        value: '清新'
    },
    {
        label: '浪漫',
        value: '浪漫'
    },
    {
        label: '伤感',
        value: '伤感'
    },
    {
        label: '治愈',
        value: '治愈'
    },
    {
        label: '放松',
        value: '放松'
    },
    {
        label: '孤独',
        value: '孤独'
    },
    {
        label: '感动',
        value: '感动'
    },
    {
        label: '兴奋',
        value: '兴奋'
    },
    {
        label: '快乐',
        value: '快乐'
    },
    {
        label: '安静',
        value: '安静'
    },
    {
        label: '思念',
        value: '思念'
    },
]
// tag的主题枚举
const selectThemeOptions: Select[] = [
    {
        label: '综艺',
        value: '综艺'
    },
    {
        label: '影视原声',
        value: '影视原声'
    },
    {
        label: 'ACG',
        value: 'ACG'
    },
    {
        label: '儿童',
        value: '儿童'
    },
    {
        label: '校园',
        value: '校园'
    },
    {
        label: '网络歌曲',
        value: '网络歌曲'
    },
    {
        label: 'KTV',
        value: 'KTV'
    },
    {
        label: '经典',
        value: '经典'
    },
    {
        label: '翻唱',
        value: '翻唱'
    },
    {
        label: '器乐',
        value: '器乐'
    }
]


// 每一行数据都要有唯一的 key
const audioRowKey = (row: AudioRowData) => row._id
// 获取数据的中数组中的index
const getAudioDataIndex = (_id: string) => {
    return audioData.findIndex((item: { _id: string; }) => item._id === _id)
}
// 是否展示原数据或者编辑栏
const ShowOrEdit: Component = defineComponent({
    props: {
        value: [String, Number, Boolean],
        onUpdateValue: [Function]
    },
    setup(props) {

        const isEdit = ref(false)
        const inputRef = ref()
        const inputValue = ref(props.value)

        function handleOnClick() {
            isEdit.value = true
            nextTick(() => {
                inputRef.value.focus()
            })
        }

        function handleChange() {
            props.onUpdateValue!(inputValue.value)
            isEdit.value = false
        }

        return () => h(
            'div',
            {
                onClick: handleOnClick
            },
            isEdit.value
                ? h(NInput as Component, {
                    ref: inputRef,
                    value: inputValue.value,
                    onUpdateValue: (v: string | number | boolean | undefined) => {
                        inputValue.value = v
                    },
                    onChange: handleChange,
                })
                : props.value
        )
    }
})


// 展示替换歌曲src的模态框
const showReplaceAudioSrcModal = ref(false)
// 展示替换歌曲cover的模态框
const showReplaceAudioCoverModal = ref(false)
// 展示替换歌词的模态框
const showReplaceLyricModal = ref(false)
// 展示替换歌曲mv的模态框
const showReplaceAudioMvModal = ref(false)
// 展示歌曲日志的模态框
const showAudioLogModal = ref(false)
// 歌曲表是否加载
const audioLoading = ref(true)
// 歌曲表ref
const audioTable = ref()
// 表单要搜索的值
const audioSearchValue = ref()
// 歌曲表checked数据
const audioCheckedRowKeys = ref<DataTableRowKey[]>([])
// 歌曲表数据
const audioData = reactive<AudioRowData[]>([])
// 歌曲表配置
const audioColumns: DataTableColumns<AudioRowData> = [
    { // selection
        type: 'selection',
    },
    { // 展开tag
        type: 'expand',
        title: 'tag',
        align: 'center',
        width: 50,
        expandable: () => true,
        renderExpand: (rowData) => {
            return h(
                'div', { style: 'display:flex;justify-content: space-around;' },
                [
                    // 请选择语种
                    h(NSelect, {
                        style: 'width:160px',
                        value: rowData.languagesTag,
                        multiple: true,
                        placeholder: "请选择语种",
                        options: selectLanguagesOptions,
                        onUpdateValue: async (value: string[]) => {
                            const result = await updateAudioInfo(rowData._id, 'languagesTag', value)
                            if (result.data.code == 0) {
                                rowData.languagesTag = value
                                message.success(result.data.message)
                            } else {
                                message.error(result.data.message)
                            }
                        }
                    }),

                    // 请选择风格
                    h(NSelect, {
                        style: 'width:160px',
                        value: rowData.styleTag,
                        multiple: true,
                        placeholder: "请选择风格",
                        options: selectStyleOptions,
                        onUpdateValue: async (value: string[]) => {
                            const result = await updateAudioInfo(rowData._id, 'styleTag', value)
                            if (result.data.code == 0) {
                                rowData.styleTag = value
                                message.success(result.data.message)
                            } else {
                                message.error(result.data.message)
                            }
                        }
                    }),

                    // 请选择场景
                    h(NSelect, {
                        style: 'width:160px',
                        value: rowData.sceneTag,
                        multiple: true,
                        placeholder: "请选择场景",
                        options: selectSceneOptions,
                        onUpdateValue: async (value: string[]) => {
                            const result = await updateAudioInfo(rowData._id, 'sceneTag', value)
                            if (result.data.code == 0) {
                                rowData.sceneTag = value
                                message.success(result.data.message)
                            } else {
                                message.error(result.data.message)
                            }
                        }
                    }),

                    // 请选择情感
                    h(NSelect, {
                        style: 'width:160px',
                        value: rowData.feelingTag,
                        multiple: true,
                        placeholder: "请选择情感",
                        options: selectFeelingOptions,
                        onUpdateValue: async (value: string[]) => {
                            const result = await updateAudioInfo(rowData._id, 'feelingTag', value)
                            if (result.data.code == 0) {
                                rowData.feelingTag = value
                                message.success(result.data.message)
                            } else {
                                message.error(result.data.message)
                            }
                        }
                    }),

                    // 请选择主题
                    h(NSelect, {
                        style: 'width:160px',
                        value: rowData.themeTag,
                        multiple: true,
                        placeholder: "请选择主题",
                        options: selectThemeOptions,
                        onUpdateValue: async (value: string[]) => {
                            const result = await updateAudioInfo(rowData._id, 'themeTag', value)
                            if (result.data.code == 0) {
                                rowData.themeTag = value
                                message.success(result.data.message)
                            } else {
                                message.error(result.data.message)
                            }
                        }
                    })
                ]
            )
        }
    },
    { // 加入时间
        key: 'joinDate',
        title: '加入时间',
        align: 'center',
        width: 100,
        render(row) {
            return `${dayjs(row.joinDate as number).format('YYYY-MM-DD HH:mm:ss')}`
        },
    },
    { // 音乐名
        key: 'audioName',
        title: '音乐名',
        align: 'center',
        width: 140,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(ShowOrEdit, {
                value: row.audioName,
                onUpdateValue: async (v: string) => {
                    // 更新数据库
                    const result = await updateAudioInfo(row._id, 'audioName', v)
                    if (result.data.code == 0) {
                        audioData[index].audioName = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    },
    { // 歌手
        key: 'singer',
        title: '歌手',
        align: 'center',
        width: 100,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(ShowOrEdit, {
                value: row.singer,
                onUpdateValue: async (v: string) => {
                    // 更新数据库
                    const result = await updateAudioInfo(row._id, 'singer', v)
                    if (result.data.code == 0) {
                        audioData[index].singer = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    },
    { // 作词
        key: 'write',
        title: '作词',
        align: 'center',
        width: 100,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(ShowOrEdit, {
                value: row.write,
                onUpdateValue: async (v: string) => {
                    // 更新数据库
                    const result = await updateAudioInfo(row._id, 'write', v)
                    if (result.data.code == 0) {
                        audioData[index].write = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    },
    { // 播放源
        key: 'audioSrc',
        title: '播放源',
        align: 'center',
        width: 80,
        render() {
            return h(NButton as Component, {
                ghost: true,
                onClick: () => { showReplaceAudioSrcModal.value = true }
            }, { default: () => '替换源' })
        },
    },
    { // 封面
        key: 'audioCover',
        title: '音频封面',
        align: 'center',
        width: 80,
        render() {
            return h(NButton as Component, {
                ghost: true,
                onClick: () => { showReplaceAudioCoverModal.value = true }
            }, { default: () => '替换源' })
        },
    },
    { // 歌词
        key: 'lyric',
        title: '歌词地址',
        align: 'center',
        width: 80,
        render() {
            return h(NButton as Component, {
                ghost: true,
                onClick: () => { showReplaceLyricModal.value = true }
            }, { default: () => '替换源' })
        },
    },
    { // mv
        key: 'audioMv',
        title: '音频视频',
        align: 'center',
        width: 80,
        render() {
            return h(NButton as Component, {
                ghost: true,
                onClick: () => { showReplaceAudioMvModal.value = true }
            }, { default: () => '替换源' })
        },
    },
    { // 专辑/来源
        key: 'audioVersion',
        title: '专辑/来源',
        align: 'center',
        width: 100,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(ShowOrEdit, {
                value: row.audioVersion,
                onUpdateValue: async (v: string) => {
                    // 更新数据库
                    const result = await updateAudioInfo(row._id, 'audioVersion', v)
                    if (result.data.code == 0) {
                        audioData[index].audioVersion = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    },
    { // 是否可用
        key: 'available',
        title: '是否可用',
        align: 'center',
        width: 100,
        render(row) {
            const index = getAudioDataIndex(row._id)
            return h(NSwitch as Component, {
                value: row.available,
                onUpdateValue: async (v: boolean) => {
                    // 更新数据库
                    const result = await updateAudioInfo(row._id, 'available', v)
                    if (result.data.code == 0) {
                        audioData[index].available = v
                        message.success(result.data.message)
                    } else {
                        message.error(result.data.message)
                    }
                }
            })
        }
    }
]
// 歌曲表页尾
const audioPagination = reactive({
    page: 1,
    itemCount: 0,
    pageSize: 4,
    prefix({ itemCount }) {
        return `你选中了 ${audioCheckedRowKeys.value.length} 行。乐库共：${itemCount} 条数据。`
    }
})


// 选中歌曲表一行
const handleCheck = (rowKeys: DataTableRowKey[]) => {
    audioCheckedRowKeys.value = rowKeys
}
// 搜索乐库
const seatchAudio = async () => {
    audioPagination.page = 1
    await updateAudioData()
}
// 展示乐库日志
const showAudioLog = () => {
    showAudioLogModal.value = true
}
// 切换歌曲表页码
const handleAudioPageChange = async (page: number) => {
    audioPagination.page = page
    await updateAudioData()
}
// 删除音频
const delteAudio = async () => {
    if (audioCheckedRowKeys.value.length !== 0) {
        for (let index = 0; index < audioCheckedRowKeys.value.length; index++) {
            const element = audioCheckedRowKeys.value[index];
            await deleteAudio(element as string)
        }
        await updateAudioData()
    } else {
        message.warning('未选中数据')
    }
}


// 更新音频数据的方法
const updateAudioData = async () => {
    // 加载audio数据并清空原数据
    audioLoading.value = true
    audioData.length = 0
    audioPagination.itemCount = 0
    audioCheckedRowKeys.value.length = 0

    if (audioSearchValue.value) {

        const result = await searchAudio(audioSearchValue.value, audioPagination.page, audioPagination.pageSize)
        if (result.data.code == 0) {
            // 加载表格数据
            result.data.data.map((v: any) => audioData.push(v))
            // 更新库中总数据
            audioPagination.itemCount = result.data.count
            // 取消加载状态
            audioLoading.value = false
        } else {
            // 取消加载状态
            audioLoading.value = false
            message.error(result.data.message)
        }

    } else {

        const result = await getAllAudio(audioPagination.page, audioPagination.pageSize)
        if (result.data.code == 0) {
            // 加载表格数据
            result.data.data.map((v: any) => audioData.push(v))
            // 更新库中总数据
            audioPagination.itemCount = result.data.count
            // 取消加载状态
            audioLoading.value = false
        } else {
            // 取消加载状态
            audioLoading.value = false
            message.error(result.data.message)
        }

    }

}

</script>
    
<style scoped lang="less">
.audio-table-nav {
    width: 100%;
    display: flex;
    margin-bottom: 8px;

}
</style>